﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BLL;
using IFactory;
using System.IO;

public partial class UserPlanWeek_SendUserPlanWeek : System.Web.UI.Page
{
    IBussinessLogic dllDepartment = new DepartmentInfoManager();
    IBussinessLogic dllUserInfo = new UserInfoManager();
    MonthPlanManager dllMonthPlanManager = new MonthPlanManager();
    MonthDateManager dllMonthDateManager = new MonthDateManager();
    VerifyCircuitManager dllVerifyCircuitManager = new VerifyCircuitManager();
    QuarterDateManager dllQuarterDateManager = new QuarterDateManager();
    QuarterPlanofManager dllQuarterPlanofManager = new QuarterPlanofManager();
    Authentication dllAuthentication = new Authentication();
    UserPlanWeek dllUserPlanWeek = new UserPlanWeek();
    WeekDateManager dllWeekDateManager = new WeekDateManager();
    Model.UserInfo objUserInfo = new Model.UserInfo();
    DataTable _powerTable = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dllAuthentication.isLogin();
        this.gdvWeekPlan.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
        this.gdvWeekPlan.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
        if (!IsPostBack)
        {
            bindDropDownList(this.drpDepartment);
            bindDropDownList(this.drpYear);
            bindDropDownList(this.drpQuarterDate);
        }
    }

    /// <summary>
    /// 根据逗号换行事件
    /// </summary>
    void wrapByComma(GridView _gridView, int _rowIndex, int _cells)
    {
        string _content = _gridView.Rows[_rowIndex].Cells[_cells].Text;
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&lt;br&gt;", "<br>");
        //_gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&gt;", ">");
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _gridView.Rows[_rowIndex].Cells[_cells].Text.Replace(",", "<br>");


    }



    /// <summary>
    /// 绑定所有的dropdownlist
    /// </summary>
    /// <param name="_drp"></param>
    void bindDropDownList(DropDownList _drp)
    {//部门绑定
        if (_drp.Equals(this.drpDepartment))
        {
            object[] _value = new object[1];
            Model.UserInfo objUserInfo = new Model.UserInfo();
            _value[0] = objUserInfo.UserName;
            DataTable _userTable = dllUserInfo.get(UserInfoManager.field.UserName.ToString(), _value);
            if (_userTable.Rows.Count > 0)
            {
                if (_userTable.Rows[0]["DepartmentId"].ToString().Length > 0)
                {
                    ListItem _li = new ListItem(_userTable.Rows[0]["DepartmentId"].ToString());
                    this.drpDepartment.Items.Add(_li);
                }
                if (_userTable.Rows[0]["PartTimeDepartmentId"].ToString().Length > 0)
                {
                    ListItem _li = new ListItem(_userTable.Rows[0]["PartTimeDepartmentId"].ToString());
                    this.drpDepartment.Items.Add(_li);
                }
            }
        }
        //年份绑定
        if (_drp.Equals(this.drpYear))
        {
            for (int i = 2009; i < 2100; i++)
            {
                ListItem _li = new ListItem(i.ToString(), i.ToString());
                _drp.Items.Add(_li);
            }
            //根据系统日期自动绑定到当前年份
            string _year = DateTime.Now.Year.ToString();
            this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year));

        }

        //绑定年计划周期
        if (_drp.Equals(this.drpQuarterDate))
        {
            object[] _value = new object[1];
            _value[0] = this.drpYear.SelectedValue;
            DataTable _quarter = dllQuarterDateManager.get(QuarterDateManager.field.QuarterYear.ToString(), _value);
            if (_quarter.Rows.Count != 0)
            {
                this.drpQuarterDate.DataSource = _quarter;
                this.drpQuarterDate.DataTextField = "QuarterName";
                this.drpQuarterDate.DataValueField = "Quarter_Id";
                this.drpQuarterDate.DataBind();
                #region dropdownlist显示系统所对应的当前年周期
                //根据系统当前日期查找到对应的年周期
                DataTable _quartertime = dllQuarterDateManager.getQuarterDate();
                //如果查到结果（结果只有一条）

                if (_quartertime.Rows.Count == 1)
                {
                    this.drpQuarterDate.SelectedIndex = this.drpQuarterDate.Items.IndexOf(this.drpQuarterDate.Items.FindByText(_quartertime.Rows[0][1].ToString()));

                }
                #endregion
                bindDropDownList(this.drpMonthDate);
            }
            else
            {
                ListItem _li = new ListItem("无年周期");
                this.drpQuarterDate.Items.Clear();
                this.drpQuarterDate.Items.Add(_li);
                bindDropDownList(this.drpMonthDate);
            }

        }

        //绑定月计划周期
        if (_drp.Equals(this.drpMonthDate))
        {
            object[] _value = new object[2];
            _value[0] = this.drpYear.SelectedValue;
            _value[1] = this.drpQuarterDate.SelectedItem.Text;
            DataTable _month = dllMonthDateManager.get(MonthDateManager.field.QuarterName.ToString(), _value);
            if (_month.Rows.Count != 0)
            {
                this.drpMonthDate.DataSource = _month;
                this.drpMonthDate.DataTextField = "MonthName";
                this.drpMonthDate.DataValueField = "Month_Id";
                this.drpMonthDate.DataBind();
                #region 根据系统当前日期绑定到当前月周期
                DataTable _monthtime = dllMonthDateManager.getMonthDate();
                if (_monthtime.Rows.Count == 1)
                {
                    this.drpMonthDate.SelectedIndex = this.drpMonthDate.Items.IndexOf(this.drpMonthDate.Items.FindByText(_monthtime.Rows[0][3].ToString()));

                }
                #endregion
                bindDropDownList(this.drpWeekDate);
            }
            else
            {
                ListItem _li = new ListItem("无月周期");
                this.drpMonthDate.Items.Clear();
                this.drpMonthDate.Items.Add(_li);
                bindDropDownList(this.drpWeekDate);
            }

        }
        //绑定周计划周期
        if (_drp.Equals(this.drpWeekDate))
        {
            object[] _value = new object[3];
            _value[0] = this.drpYear.SelectedValue;
            _value[1] = this.drpQuarterDate.SelectedItem.Text;
            _value[2] = this.drpMonthDate.SelectedItem.Text;
            DataTable _week = dllWeekDateManager.get(WeekDateManager.field.MonthName.ToString(), _value);
            if (_week.Rows.Count != 0)
            {
                this.drpWeekDate.DataSource = _week;
                this.drpWeekDate.DataTextField = "WeekName";
                this.drpWeekDate.DataValueField = "Week_Id";
                this.drpWeekDate.DataBind();
                DataTable _weektime = dllWeekDateManager.getWeekDate();
                if (_weektime.Rows.Count == 1)
                {
                    this.drpWeekDate.SelectedIndex = this.drpWeekDate.Items.IndexOf(this.drpWeekDate.Items.FindByText(_weektime.Rows[0][4].ToString()));
                    if (Request.Params["Id"] != null && Request.Params["Id"].ToString().Length != 0)
                    {

                        this.drpWeekDate.SelectedIndex = this.drpWeekDate.Items.IndexOf(this.drpWeekDate.Items.FindByValue(Request.Params["Id"].ToString()));

                    }

                }
                bindGridView();
            }
            else
            {
                ListItem _li = new ListItem("无周周期");
                this.drpWeekDate.Items.Clear();
                this.drpWeekDate.Items.Add(_li);
                this.gdvWeekPlan.DataSource = new DataTable();
                bindGridView();
            }

        }

    }
    /// <summary>
    /// 绑定gridview
    /// </summary>
    void bindGridView()
    {
        if (this.drpWeekDate.SelectedItem.Text != "无周周期")
        {
            object[] _value = new object[3];
            Model.UserInfo objUserInfo = new Model.UserInfo();
            _value[0] = objUserInfo.UserName;
            _value[1] = this.drpDepartment.SelectedItem.Text;
            _value[2] = Convert.ToInt32(this.drpWeekDate.SelectedItem.Value);
            DataTable _weekPlan = dllUserPlanWeek.getSendUserPlanWeek(_value);
            DataView dv = new DataView(_weekPlan);
            dv.Sort = "WeekPlanSortId";
            this.gdvWeekPlan.DataSource = dv;
            this.gdvWeekPlan.DataBind();
        }
        else
        {
            this.gdvWeekPlan.DataSource = new DataTable();
            this.gdvWeekPlan.DataBind();
        }
        #region
        for (int i = 0; i < this.gdvWeekPlan.Rows.Count; i++)
        {
            LinkButton lbtn = (LinkButton)gdvWeekPlan.Rows[i].Cells[1].FindControl("lbtnSource");
            lbtn.Text = gdvWeekPlan.DataKeys[i]["Source"].ToString();
            if (this.gdvWeekPlan.DataKeys[i]["AttachmentPath"].ToString().Length == 0)
            {
                Button _btn = (Button)this.gdvWeekPlan.Rows[i].Cells[13].FindControl("btnDownLoad");
                _btn.Visible = false;
                Label _lbl = (Label)this.gdvWeekPlan.Rows[i].Cells[13].FindControl("lblAlert");
                _lbl.Visible = true;
                _lbl.Text = "无下载";
            }
            wrapByComma(this.gdvWeekPlan, i, 7);
            wrapByComma(this.gdvWeekPlan, i, 8);
            if (this.gdvWeekPlan.Rows[i].Cells[12].Text != "&nbsp;" && this.gdvWeekPlan.Rows[i].Cells[12].Text != "")
            {
                this.gdvWeekPlan.Rows[i].Cells[12].Text = "";
            }
            if (this.gdvWeekPlan.Rows[i].Cells[9].Text != "&nbsp;" && this.gdvWeekPlan.Rows[i].Cells[9].Text != "")
            {
                this.gdvWeekPlan.Rows[i].Cells[9].Text = "";
            }
        }
        #endregion

    }
    #region dropdownlist索引改变事件
    /// <summary>
    /// 年份改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindDropDownList(this.drpQuarterDate);
        bindDropDownList(this.drpMonthDate);
        if (this.drpMonthDate.Text != "无月周期")
        {
            bindGridView();
        }
        else
        {
            this.gdvWeekPlan.DataSource = new DataTable();
            this.gdvWeekPlan.DataBind();
        }
    }
    /// <summary>
    /// 年周期改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpQuarterDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindDropDownList(this.drpMonthDate);

    }
    /// <summary>
    /// 月周期改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpMonthDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindDropDownList(this.drpWeekDate);
    }
    /// <summary>
    /// 周周期改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpWeekDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindGridView();
    }
    /// <summary>
    /// 自动分页事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gdvWeekPlan_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gdvWeekPlan.PageIndex = e.NewPageIndex;
        bindGridView();
    }
    #endregion

    /// <summary>
    /// 流程按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnVerifyCircuit_Click(object sender, EventArgs e)
    {
        int _count = 0;
        string _url = "";
        int _weekId = 0;
        for (int i = 0; i < this.gdvWeekPlan.Rows.Count; i++)
        {
            CheckBox chk = (CheckBox)this.gdvWeekPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (chk.Checked == true)
            {
                _count++;
                _weekId = Convert.ToInt32(this.gdvWeekPlan.DataKeys[i]["WeekPlanId"].ToString());

            }
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个周计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
        _url = "../WebCommon/VerifyCircruitForUserPlanDisplay.aspx?PlanId=" + _weekId + "&PlanType=5";
        Page.RegisterStartupScript("windowOpen",
           "<script language=javascript>window.open('" + _url + "','newwindow','height=150,width=550,top=250,left=300,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");

    }
    /// <summary>
    /// 撤回按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        int _count = 0;
        List<object[]> _valuelist = new List<object[]>();
        string _alert = "";
        for (int i = 0; i < this.gdvWeekPlan.Rows.Count; i++)
        {
            CheckBox chk = (CheckBox)this.gdvWeekPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (chk.Checked == true)
            {
                _count++;
                object[] _value = new object[1];
                _value[0] = Convert.ToInt32(this.gdvWeekPlan.DataKeys[i]["WeekPlanId"].ToString());


                int state = Convert.ToInt32(this.gdvWeekPlan.DataKeys[i]["PlanSendState"].ToString());
                if (state < 2)
                {
                    _valuelist.Add(_value);
                }
                else
                {
                    _alert += this.gdvWeekPlan.DataKeys[i]["WeekPlanSortId"].ToString() + ",";
                }

              
            }
        }

        if (_count == 0)
        {
            Utility.HttpHelp.alert("选择一条周计划", Page);
            return;
        }

        if (_valuelist.Count > 0)
        {
            int _result = dllUserPlanWeek.editWithTransaction(UserPlanWeek.field.Sponsor.ToString(), _valuelist);

            if (_result == 0)
            {
                Utility.Error.RedirectErrorPage("撤回周计划未成功，请重试");
            }
            else
            {
                Response.Redirect("SendUserPlanWeek.aspx");
            }
        }

        if (_alert.Length > 0)
        {
            Utility.HttpHelp.alert("计划编号为" + _alert + "的计划不可撤回，因为对应的周计划已经审核完毕", Page);
        }

    }
    /// <summary>
    /// 上传文件事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAttachmentPath_Click(object sender, EventArgs e)
    {
        string _weekId = "";

        int _count = 0;
        for (int i = 0; i < this.gdvWeekPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvWeekPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                _weekId = this.gdvWeekPlan.DataKeys[i]["WeekPlanId"].ToString();
                _count++;
            }
        }
        if (_count == 1)
        {
            //定向到添加年附件路径页面
            string _url = "../WebCommon/SendAttachmentPath.aspx?PlanId=" + _weekId + "&PlanType=8";
            Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "','quarterplandetailmodify','height=40,width=400,top=300,left=300,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');</script>");            
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
    }
    /// <summary>
    /// 下载按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDownLoad_Click(object sender, EventArgs e)
    {
        int i = 0;
        Button btt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)btt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        i = iRow.RowIndex;//得到该行的索引
        //读取隐藏地址列
        string path = this.gdvWeekPlan.DataKeys[i]["AttachmentPath"].ToString();
        FileDownload(path);
       // Utility.HttpHelp.DownloadFile(path);
    }

    ///   <summary>   
    ///   文件下载   
    ///   </summary>   
    ///   <param   name="FullFileName"></param>   
    private void FileDownload(string strFileName)
    {

        FileInfo DownloadFile = new FileInfo(strFileName);
        if (!DownloadFile.Exists)
        {
            Utility.HttpHelp.alert("无附件,请与管理员联系", Page);
            return;
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = false;
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName.Substring(strFileName.LastIndexOf('\\') + 1), System.Text.Encoding.UTF8));
        // Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());

        Response.WriteFile(DownloadFile.FullName);
        Response.Flush();
        Response.End();

    }
    /// <summary>
    /// 全选事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <author>grokyao</author>
    /// <date>2009-3-6</date>
    protected void ckbAllSelect_CheckedChanged(object sender, EventArgs e)
    {
        if (this.ckbAllSelect.Checked == true)
        {
            for (int i = 0; i < this.gdvWeekPlan.Rows.Count; i++)
            {
                CheckBox ckb = (CheckBox)this.gdvWeekPlan.Rows[i].Cells[0].FindControl("ckbSelect");
                ckb.Checked = true;
            }
        }
        else
        {
            for (int i = 0; i < this.gdvWeekPlan.Rows.Count; i++)
            {
                CheckBox ckb = (CheckBox)this.gdvWeekPlan.Rows[i].Cells[0].FindControl("ckbSelect");
                ckb.Checked = false;
            }
        }
    }


    /// <summary>
    /// 计划链接事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lbtnSource_Click(object sender, EventArgs e)
    {
        int i = 0;
        LinkButton bt = (LinkButton)sender;//获得当前控件
        TableCell cell = (TableCell)bt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行         
        i = iRow.RowIndex;//得到该行的索引
        Control c = (Control)iRow.Parent;
        GridView _gdv = (GridView)c.Parent;
        int _monthPlanId = Convert.ToInt32(_gdv.DataKeys[i]["MonthPlanId"].ToString());
        if (_monthPlanId == 0)
        {
            //新增的不链接页面
        }
        else
        {
            string _url = "MonthPlanDetail.aspx?MonthPlanId=" + _monthPlanId;
            Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "','newwindow','height=160,width=900,top=200,left=50,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");
        }
    }
}
